import {onMounted, onUnmounted, ref} from "vue";

/**
 * * 生成一个不重复的ID
 * @param { Number } randomLength
 */
export const getUUID = (randomLength = 10) => {
    return Number(Math.random().toString().substring(2, randomLength) + Date.now()).toString(36)
}

/**
 * 获取本地图
 * @param name // 文件名 如 doc.png
 * @returns {*|string}
 */
export function getAssetsImages(name) {
    return new URL(`../assets/images/${name}`, import.meta.url).href;
}

/**
 * 参数处理
 * @param {*} params  参数
 */
export function tansParams(params) {
    let result = ''
    for (const propName of Object.keys(params)) {
        const value = params[propName];
        var part = encodeURIComponent(propName) + "=";
        if (value !== null && value !== "" && typeof (value) !== "undefined") {
            if (typeof value === 'object') {
                for (const key of Object.keys(value)) {
                    if (value[key] !== null && value[key] !== "" && typeof (value[key]) !== 'undefined') {
                        let params = propName + '[' + key + ']';
                        var subPart = encodeURIComponent(params) + "=";
                        result += subPart + encodeURIComponent(value[key]) + "&";
                    }
                }
            } else {
                result += part + encodeURIComponent(value) + "&";
            }
        }
    }
    return result
}

// 验证是否为blob格式
export function blobValidate(data) {
    return data.type !== 'application/json'
}

/**
 * 使用postcss只能处理css，不能处理js，echart中的size一般是存在js中的，所以需要处理js中的size，从而改使echart中的字号自适应
 * */
export function useEchartSize() {
    const curRatio = ref(1)

    let timer = null;
    onMounted(() => {
        // 初始化时候不设置延时，则不会出现闪屏得效果
        resizeHandler()
        window.addEventListener('resize', resizeChartSize)
    })
    onUnmounted(() => {
        window.removeEventListener('resize', resizeChartSize)
    })

    const resizeChartSize = () => {
        if (timer) {
            clearTimeout(timer);
        }
        timer = setTimeout(() => {
            resizeHandler()
        }, 300)
    }

    const resizeHandler = () => {
        let windowWidth = window.innerWidth;
        let baseWidth = 11520
        curRatio.value = windowWidth / baseWidth;
    }

    return {
        curRatio
    }
}
